package socket;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-10-28
 * Time: 21:06
 */

//实现回声服务器
public class UdpEchoServer {
    //网络编程大前提
    private DatagramSocket socket = null;

    //构造方法指定端口号
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!");
        //接收客户端发来的请求 UDP数据传输的基本单位是DatagramPacket 不断的接收
        //要有一个空的Packet对象来接收 指定大小
        while (true){
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);//接收发来的请求
            //将请求解析成字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength(),"UTF-8");
            //业务逻辑
            String response = process(request);
            System.out.println(request);
            //将返回的数据打包成DatagramPacket对象                注意细节response.getBytes().length,
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket); //发送返回给客户端
            System.out.println("地址: " + responsePacket.getAddress() + " req:" + request + " resp:" + response);
        }

    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
